<template>
  <el-card class="page-container">
    <template #header>
      <div class="header" style="display: flex">
        <div class="title">{{ title }}</div>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form class="form-inline" ref="adminFormRef" :model="adminForm" :rules="rules" label-width="120px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="adminForm.username" disabled v-if="id"></el-input>
            <el-input v-model="adminForm.username" v-else></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="adminForm.name"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="saveHandle">保存</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElForm, ElMessage, FormRules } from 'element-plus'
import { AdminData } from '@/types/admin'
import { addAdminAPI, getAdminAPI, putAdminAPI } from '@/api/admin/admin'
const router = useRouter()
const route = useRoute()
// 员工id
const id = route.query.id as number | null
// 标题
const title = ref('')
// 员工信息表单
const adminForm = ref({} as AdminData)
onMounted(async () => {
  try {
    if (!id) {
      title.value = '添加管理员'
    } else {
      title.value = '修改管理员'
      // 获取员工信息
      let res = await getAdminAPI(id)
      adminForm.value = res.data
    }
  } catch (error) {
    console.log(error)
  }
})
// 表单实例
const adminFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 校验规则
const rules = reactive<FormRules<typeof adminForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    {
      min: 2,
      max: 10,
      message: '长度为2~10个非空字符且只能为数字或字母',
      trigger: 'submit',
    },
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
})
// 保存员工信息
const saveHandle = async () => {
  adminFormRef.value?.validate(async (vaild: boolean) => {
    if (vaild) {
      if (title.value === '修改管理员') {
        const params = {
          ...adminForm.value,
        }
        await putAdminAPI(params)
        ElMessage.success('修改成功')
        router.back()
      } else if (title.value === '添加管理员') {
        const params = {
          ...adminForm.value,
        }
        await addAdminAPI(params)
        ElMessage.success('添加成功')
        router.back()
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>
<style scoped lang="scss"></style>
